<template>
  <el-dialog
    class="add-input-material-comp"
    title="新增进场材料"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :visible="visible"
    :width="$setRem(980)"
    :before-close="handleCancel">
    <el-form
      element-loading-custom-class="custom-load"
      :model="ruleForm"
      :rules="rules"
      label-suffix="："
      size="medium"
      ref="ruleForm"
      :label-width="$setRem(140)"
      class="rule-form"
    >
      <el-row>
        <el-col :span="11">
          <el-form-item label="材料名称" prop="materialTypeId" required>
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.materialTypeName || '' }}</span>
            <el-select
              v-else
              filterable
              remote
              v-model="ruleForm.materialTypeId"
              placeholder="请输入材料名称"
              :remote-method="remoteMethod"
              :loading="selectLoading">
              <el-option
                v-for="item in materialList"
                :key="item.id"
                :label="item.materialName"
                :value="item.id">
                {{ item.materialName }}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="规格/型号" prop="model" required>
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.model || '' }}</span>
            <el-select
              v-else
              placeholder="请选择规格/型号"
              filterable
              v-model="ruleForm.model">
              <el-option
                v-for="v in modelList"
                :label="v.modelName"
                :value="v.modelName"
                :key="v.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="11">
          <el-form-item label="材料数量" prop="materialNum" required>
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.materialNum || 0 }}</span>
            <el-input-number
              v-else
              :min="0"
              clearable
              placeholder="请输入材料数量"
              v-model="ruleForm.materialNum">
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="单位" prop="unit" required>
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.unit || '' }}</span>
            <el-input
              v-else
              type="text"
              :disabled="!ruleForm.unit"
              placeholder="单位"
              :value="ruleForm.unit">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="11">
          <el-form-item label="收货人" prop="receiveUser" required>
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.receiveUserName || '' }}</span>
            <el-select
              v-else
              placeholder="请选择收货人"
              filterable
              v-model="ruleForm.receiveUser">
              <el-option
                v-for="v in userList"
                :label="v.userName"
                :value="v.uuid"
                :key="v.uuid">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="收货单位" prop="receiveCompany">
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.receiveCompany || '' }}</span>
            <el-input
              v-else
              type="text"
              placeholder="请输入收货单位"
              v-model="ruleForm.receiveCompany">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="11">
          <el-form-item label="材料厂家" prop="materialFactory" required>
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.materialFactory || '' }}</span>
            <el-input
              v-else
              type="text"
              placeholder="请输入材料厂家"
              v-model="ruleForm.materialFactory">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="验收合格" prop="acceptFlag" required>
            <span class="detail-text" v-if="hasDetail">
              {{ ruleForm.acceptFlag === '1' ? '合格' : '不合格' }}
            </span>
            <el-switch
              v-else
              v-model="ruleForm.acceptFlag"
              active-value="1"
              inactive-value="0"
              active-text="合格"
              inactive-text="不合格"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row style="width: 50%; float: left;">
        <el-col :span="11">
          <el-form-item label="进场日期" prop="approachDate" required>
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.approachDate || '' }}</span>
            <el-date-picker
              v-else
              v-model="ruleForm.approachDate"
              format="yyyy-MM-d"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="请选择进场日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row style="width: 50%; float: right; z-index: 1;">
        <el-col :span="11">
          <el-form-item label="检测报告" prop="inspectUrl">
            <div v-if="ruleForm.inspectUrl || hasDetail" class="image-list">
              <div v-if="!hasDetail" class="mask">
                <i class="el-icon-delete" @click="handleRemovePic('inspectUrl')"></i>
              </div>
              <img :src="$checkUrl(ruleForm.inspectUrl)" class="avatar" />
            </div>
            <el-upload
              v-else
              class="avatar-uploader"
              action="#"
              accept=".jpg,.png,.jpeg"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="beforeInspectUrlUpload">
              <i v-if="picLoading" class="el-icon-loading avatar-loading-icon"></i>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row style="width: 50%; float: left;" class="annex">
        <el-form-item label="附件" prop="annexUrl" required>
          <div v-if="ruleForm.annexUrl || hasDetail" class="image-list">
            <div v-if="!hasDetail" class="mask">
              <i class="el-icon-delete" @click="handleRemovePic('annexUrl')"></i>
            </div>
            <img :src="$checkUrl(ruleForm.annexUrl)" class="avatar" />
          </div>
          <el-upload
            v-else
            class="avatar-uploader"
            action="#"
            accept=".jpg,.png,.jpeg"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="beforeAnnexUrlUpload">
            <i v-if="annexUrlLoading" class="el-icon-loading avatar-loading-icon"></i>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-row>

      <el-row style="clear: both;" >
        <el-col :span="11">
          <el-form-item label="抄送人员" prop="copyUser">
            <span class="detail-text" v-if="hasDetail">{{ ruleForm.copyUserName || '' }}</span>
            <el-select
              v-else
              placeholder="请选择抄送人员"
              :multiple="false"
              clearable
              filterable
              v-model="ruleForm.copyUser">
              <el-option
                v-for="v in userList"
                :label="v.userName"
                :value="v.uuid"
                :key="v.uuid">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button
        size="medium"
        type="primary"
        v-if="!hasDetail"
        :loading="loading"
        @click="hanldeSave('2')">
        提 交
      </el-button>
      <el-button
        size="medium"
        type="primary"
        v-if="!hasDetail"
        :loading="loading"
        @click="hanldeSave('1')">
        暂 存
      </el-button>
      <el-button size="medium" @click="handleCancel">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'add'
    },
    options: {
      type: Object,
      default: () => ({})
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      userList: [],
      materialList: [],
      modelList: [],
      picLoading: false,
      annexUrlLoading: false,
      selectLoading: false,
      ruleForm: {
        id: '',
        materialTypeId: '',
        materialTypeName: '',
        materialNum: '',
        materialFactory: '',
        unit: '',
        model: '',
        receiveUser: '',
        receiveUserName: '',
        receiveCompany: '',
        copyUser: '',
        copyUserName: '',
        inspectUrl: '',
        annexUrl: '',
        acceptFlag: '1',// （0：不合格；1：合格）
        approachDate: this.$moment().format('YYYY-MM-DD')
      },
      rules: {
        materialTypeId: [
          { required: true, message: '请输入材料名称' },
        ],
        model: [
          { required: true, message: '请选择规格/型号' },
        ],
        materialNum: [
          { required: true, message: '请输入材料数量' },
        ],
        materialFactory: [
          { required: true, message: '请输入材料厂家' },
        ],
        unit: [
          { required: true, message: '单位不能为空' },
        ],
        receiveUser: [
          { required: true, message: '请选择收货人' },
        ],
        // receiveCompany: [
        //   { required: true, message: '收货单位不能为空' },
        // ],
        annexUrl: [
          { required: true, message: '请上传附件' },
        ],
        copyUser: [
          { required: true, message: '请选择抄送人员' },
        ],
        approachDate: [
          { required: true, message: '请选择时间' },
        ],
      },
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    // 新增
    hasAdd() {
      return this.type === 'add';
    },
    // 编辑
    hasEdit() {
      return this.type === 'edit';
    },
    hasDetail() {
      return this.type === 'detail';
    },
    // 当前抄送人信息
    currentCopyUser() {
      return this.userList.find(v => (
        v.uuid === this.ruleForm.copyUser
      )) || {};
    },
    // 当前收货人信息
    currentReceiveUser() {
      return this.userList.find(v => (
        v.uuid === this.ruleForm.receiveUser
      )) || {};
    },
    // 当前选中的材料
    currentMaterialData() {
      return this.materialList.find(v => (
        v.id === this.ruleForm.materialTypeId
      ));
    }
  },
  watch: {
    options: {
      deep: true,
      handler(data) {
        const keys = Object.keys(this.ruleForm);
        data && Object.keys(data).length && keys.forEach(key => {
          this.ruleForm[key] = data[key] || '';
        });
      }
    },
    visible(value) {
      if (!value) {
        Object.keys(this.ruleForm).forEach(key => {
          this.ruleForm[key] = key === 'approachDate'
            ? this.$moment().format('YYYY-MM-DD')
            : '';
        });
      }
    },
    'ruleForm.receiveUser'(val) {
      if (val) {
        const current = this.userList.find(v => v.uuid === val);
        if (current) {
          this.ruleForm.receiveUserName = current.userName;
          // this.ruleForm.receiveCompany = current.organizationName;
        }
      }
    },
    'ruleForm.copyUser'(val) {
      if (val) {
        const current = this.userList.find(v => v.uuid === val);
        if (current) this.ruleForm.copyUserName = current.userName;
      }
    },
    'ruleForm.materialTypeId'(val) {
      if (val) {
        this.getStockModelList();
        const current = this.materialList.find(v => v.uuid === val);
        if (current) {
          this.ruleForm.materialTypeName = current.materialName;
        }
      }
    },
    currentMaterialData: {
      deep: true,
      handler(data) {
        if (data) this.ruleForm.unit = data.unit;
      }
    }
  },
  created() {
    this.getUserList();
    this.getStockTypeList();
  },
  methods: {
    // 获取材料类型
    async getStockTypeList(options = {}) {
      const params = {
        pageSize: 100,
        pageNum: 1,
        projectId: this.projectId,
        ...options
      };
      const { success, data: {
        data
      }} = await this.$Model.getStockTypeList(params);
      if (success && data) {
        this.materialList = data.list || [];
      }
    },
    // 根据类型id查询规格集合
    async getStockModelList() {
      if (!this.ruleForm.materialTypeId) return;
      const params = {
        id: this.ruleForm.materialTypeId
      };
      const { success, data: {
        data
      }} = await this.$Model.getStockModelList(params);
      if (success && data) this.modelList = data;
    },
    /**
     * 获取用户列表数据
     */
    async getUserList() {
      const params = {
        pageFlag: false
      };
      const { success, data: {
        data
      }} = await this.$Model.getUserList(params);
      if (success && data) {
        this.userList = data.list || [];
      }
    },
    handleCancel() {
      this.$emit('cancel');
    },
    // 材料搜索
    querySearchAsync(queryString, callback) {
      callback([333]);
    },
    // 材料名称搜索
    remoteMethod(query) {
      this.selectLoading = true;
      setTimeout(async () => {
        await this.getStockTypeList({
          condition: query
        });
        this.selectLoading = false;
      }, 200);
    },
    // 上传图片
    async beforeInspectUrlUpload(file) {
      const fm = new FormData();
      fm.append('file', file.raw);
      this.picLoading = true;
      const { success, data: { data }} = await this.$Model.fileUpload(fm);
      this.picLoading = false;
      if (success) {
        this.ruleForm.inspectUrl = data;
      }
    },
    // 上传图片
    async beforeAnnexUrlUpload(file) {
      const fm = new FormData();
      fm.append('file', file.raw);
      this.annexUrlLoading = true;
      const { success, data: { data }} = await this.$Model.fileUpload(fm);
      this.annexUrlLoading = false;
      if (success) {
        this.ruleForm.annexUrl = data;
      }
    },
    // 删除图片
    async handleRemovePic(type) {
      if (!this.ruleForm[type]) return;
      this.ruleForm[type] = '';
      const params = {
        filePath: this.ruleForm[type]
      };
      this.$Model.fileDelete(params, { showErr: false });
    },
    hanldeSave(status) {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = {
            status,
            ... this.ruleForm
          };
          this.$emit('submit', params);
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
  @import '../../../assets/styles/dialog';

  .add-input-material-comp {

    .avatar-uploader {
      .el-upload {
        position: relative;
      }
    }
    .image-list {
      width: 100%;
      height: 100%;
      position: relative;
      transition: all .3s;
      .mask {
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0;
        top: 0;
        cursor: pointer;
        text-align: center;
        color: #fff;
        opacity: 0;
        font-size: 20px;
        background-color: rgba(0,0,0,.5);
        transition: opacity .3s;
        &:hover {
          opacity: 1;
        }
      }
      .avatar {
        width: 100%;
        height: 100%;
      }
      .el-icon-delete {
        position: absolute;
        top: calc(50% - 10px);
        left: calc(50% - 10px);
      }
    }
    .avatar-loading-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
      border-radius: 6px;
      &:hover {
        color: $mainColor;
      }
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      &:hover {
        border-color: $mainColor;
        color: $mainColor;
      }
    }
    .detail-text {
      color: $mainColor;
    }
    .annex {
      /deep/ .el-form-item__content {
        .image-list {
          width: 120px;
        }
      }
    }
    /deep/ .el-form-item {
      .el-switch__label {
        color: #fff;
        &.is-active {
          color: $mainColor;
        }
      }
    }
  }
</style>
